package com.wolfpire.workflow.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.workflow.dao.NodeActorDao;
import com.wolfpire.workflow.om.NodeActor;

@Repository("nodeActorDao")
public class NodeActorDaoImpl extends BaseHibernateDao<NodeActor, Long> implements NodeActorDao {
	
	/**
	 * 
	 * @param nodeId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<NodeActor> queryNodeActors(Long nodeId) {
		Criteria criteria = createCriteria(Restrictions.eq("nodeId", nodeId));
		criteria.addOrder(Order.desc("actorName"));
		return criteria.list();
	}
	
	/**
	 * 根据节点ID获取该节点参与者列表
	 * @param nodeId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> queryNodeActorListByNodeId(Long nodeId) {
		
		String sql = "SELECT T.PROPERTY_ID, T.ACTOR_TYPE, T.ACTOR_ID, T.ACTOR_NAME FROM  WF_NODE_ACTOR T WHERE T.NODE_ID=?";
		sql += " ORDER BY T.ACTOR_NAME ASC ";
		Query query = getSession().createSQLQuery(sql);
		query.setParameter(0, nodeId);
		return query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<String> queryNodeActorsByNodeId(Long nodeId) {
		
		String sql = "SELECT T.ACTOR_ID FROM  WF_NODE_ACTOR T WHERE T.NODE_ID=?";
		
		Query query = getSession().createSQLQuery(sql);
		query.setParameter(0, nodeId);
		return query.setResultTransformer(CriteriaSpecification.ROOT_ENTITY).list();
	}
	
	/**
	 * 根据节点ID删除节点参与者
	 * @param nodeId
	 */
	public void deleteNodeActorsByNodeId(Long nodeId) {
		String sql = "delete  WF_NODE_ACTOR T WHERE T.NODE_ID=?";
		
		Query query = getSession().createSQLQuery(sql);
		query.setParameter(0, nodeId);
		query.executeUpdate();
	}
	
	/**
	 * 根据流程定义ID和节点名称获取节点参与者列表
	 * @param deploymentId
	 * @param nodeName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> queryNodeActors(Long deploymentId, String nodeName){
		String sql = "SELECT T.PROPERTY_ID, T.ACTOR_TYPE, T.ACTOR_ID, T.ACTOR_NAME FROM  WF_NODE_ACTOR T LEFT JOIN  WF_NODE T1 ON T.NODE_ID=T1.NODE_ID WHERE T1.DEPLOYMENT_ID=? AND T1.NODE_NAME=?";
		
		Query query = getSession().createSQLQuery(sql);
		query.setParameter(0, deploymentId);
		query.setParameter(1, nodeName);
		return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	}

}
